package com.ideal.hadoopadmin.service.cluster;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ideal.hadoopadmin.common.entity.ResultAPI;
import com.ideal.hadoopadmin.common.framework.orm.SearchFilter;
import com.ideal.hadoopadmin.entity.cluster.ClusterMachine;
import com.ideal.hadoopadmin.entity.cluster.ClusterUser;
import com.ideal.hadoopadmin.mapper.webdb.cluster.ClusterMachineMapper;
import com.ideal.tools.ssh.entity.LinuxMachine;
import com.ideal.tools.ssh.result.LinuxResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 袁颖 on 2016/2/19.
 */
@Service
public class ClusterMachineService {
    @Resource
    ClusterMachineMapper clusterMachineMapper;
    //ClusterUserService类重新为NewClusterUserService类update20160802qinfengxia
    //@Resource
    //ClusterUserService clusterUserService;
    @Autowired
    ClusterUserServiceNew clusterUserService;

    /**
     * 通过不同的条件进行分页查询
     *
     * @param searchParams
     */
    public PageInfo searchClusterMachine(Map<String, Object> searchParams, HttpServletRequest request) {
        //从前台获取当前页码
        int currentPage = Integer.parseInt(request.getParameter("page") == null ? "1" : request.getParameter("page"));
        //过滤器
        String where = SearchFilter.parseToString(searchParams);
        //使用分页
        PageHelper.startPage(currentPage, 10);
        //加入组织好的where 条件
        PageHelper.setAppendWhere(where);
        List<ClusterMachine> clusterMachines = clusterMachineMapper.findAllClusterMachine();
        PageInfo page = new PageInfo(clusterMachines);
        return page;
    }

    /**
     * 查询某个集群的所有机器ip用于自动补全
     *
     * @return
     */
    public List<String> findAllIp() {
        return clusterMachineMapper.findAllIp();
    }

    public List<String> findAllUser() {
        return clusterMachineMapper.findAllUser();
    }

    public ClusterMachine findById(Long id) {
        return clusterMachineMapper.findById(id);
    }

    public void saveClusterMachine(ClusterMachine clusterMachine) {
        //如果之前已经存在就更新数据，否则进行保存
        if (clusterMachine.getId() != null) {
            clusterMachineMapper.updateClusterMachine(clusterMachine);
        } else {
            clusterMachineMapper.saveClusterMachine(clusterMachine);
        }
    }

    //检查机器的ip，命名和集群id是否全部相同，如相同，则冲突返回seccess.
    public String checkClusterMachine(ClusterMachine clusterMachine) {
        ClusterMachine newClusterMachine = clusterMachineMapper.findByUserIpType(clusterMachine);
        if (newClusterMachine != null && clusterMachine.getId() != newClusterMachine.getId()) {//集群机器存在
            return "success";//存在冲突

        } else {
            return "error";//不存在冲突
        }
    }

    public void deleteClusterMachine(Long id) {
        clusterMachineMapper.deleteClusterMahine(id);
    }

    //获取指定的机器,如果为null获取所有的
    public List<LinuxMachine> getMachineList(List<Long> machineTypeIds) {
        //需要传一个参数,只需要查找某一个类型的
        List<ClusterMachine> clusterMachines = clusterMachineMapper.findAllClusterMachine();
        //对所有的machine进行处理,获取想要的machineList
        List<ClusterMachine> newClusterMachines = new ArrayList<ClusterMachine>();
        for(ClusterMachine newclusterMachine:clusterMachines){
            if(machineTypeIds==null||machineTypeIds.contains(newclusterMachine.getMachineType().getMachineTypeId())){
                newClusterMachines.add(newclusterMachine);
            }
        }
        return getLinuxMachine(newClusterMachines);
    }
    public List<LinuxMachine> getLinuxMachine(List<ClusterMachine> clusterMachines){
        List<LinuxMachine> linuxMachines = new ArrayList<LinuxMachine>();
        for (ClusterMachine clusterMachine : clusterMachines) {
            LinuxMachine linuxMachine = new LinuxMachine();
            linuxMachine.initIP(clusterMachine.getMachineIp());
            linuxMachine.initLoginName(clusterMachine.getLoginUserName());
            linuxMachine.initPassWord(clusterMachine.getLoginPassWord());
            linuxMachine.initMachineType(LinuxMachine.MachineType.getEnumMachineType(clusterMachine.getMachineType().getMachineTypeName()));
            linuxMachines.add(linuxMachine);
        }
        return linuxMachines;
    }
    //通过machineType查找clusterMachine
   public List<ClusterMachine> findByMachineTypeId(Long machineTypeId){
       return clusterMachineMapper.findByMachineTypeId(machineTypeId);
   }
    //查找机器对应的client配置
    public List<Map<String,Object>> findMachineAndClientquota(Long machineTypeId,Long userId){
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("machineTypeId",machineTypeId);
        if(null != userId && !"".equals(userId)){
            map.put("userId",userId);
            return clusterMachineMapper.findMachineAndClientquota(map);
        }else {
            return clusterMachineMapper.findMachine(map);
        }

    }

    public String getMachineIpsByIds(String machineIds){
        String[] machineId = machineIds.split(",");
        String machineIps = "";
        for(int i=0;i<machineId.length;i++){
            ClusterMachine clusterMachine = clusterMachineMapper.findById(Long.parseLong(machineId[i].trim()));
            machineIps += clusterMachine.getMachineIp()+",";
        }
        if(StringUtils.isNotBlank(machineIps)){//如果不为null或空字符串的时候,去掉最后一个逗号
            machineIps = machineIps.substring(0,machineIps.length()-1);
        }
        return machineIps;
    }

    /*根据ip查找类型为client的机器id*/
    public Long getMachineIdByIpAndType(String ip,Long clusterTypeId){
        return clusterMachineMapper.findMachineIdByIpAndType(ip,clusterTypeId);
    }
    public List<String> saveSynchrony(Long userId,String machineIds){
        ClusterUser clusterUser = clusterUserService.queryClusterUserById(userId);
        String machineIps = getMachineIpsByIds(machineIds);
        List<LinuxResult> linuxResults = clusterUserService.addClientUserAPI(clusterUser, machineIps);
        ResultAPI.initAPIResult(linuxResults);
        return ResultAPI.messageList;
    }
   public List<ClusterMachine> findAllMachine(){
      return clusterMachineMapper.findAllClusterMachine();
   }
}

